﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ExcelUnity.Importer.Wrappers.SheetDataBuilders
{
    public class DefaultDataBuilder
    {
        public static object CreateDefaultDataList(List<RowWrapper>? rows, List<ColumnWrapper>? columns, Type dataType)
        {
            var modelList = Activator.CreateInstance(typeof(List<>).MakeGenericType(new Type[] { dataType }));
            if (rows == null || columns == null)
                return modelList;

            var addMethod = modelList.GetType().GetMethod("Add");

            var columnPropertyDic = columns.Where(x => x.ColumnProperty != null).ToDictionary(m => m.ColumnIndex);
            if (columnPropertyDic.Count == 0) return modelList;

            foreach (var row in rows)
            {
                var dataModel = Activator.CreateInstance(dataType);
                foreach (var cellWrapper in row.Cells)
                {
                    if (columnPropertyDic.TryGetValue(cellWrapper.ColumnIndex, out ColumnWrapper wrapper))
                        wrapper.ColumnProperty!.FillDataPropertyValue(cellWrapper.Value, dataModel, (_, err) => cellWrapper.AppendError(err!));
                }

                row.ModelData = dataModel;
                addMethod.Invoke(modelList, new object[] { dataModel });
            }

            return modelList;
        }
    }
}
